package com.gitee.sop.notifyexample.service;

import com.gitee.sop.notify.api.NotifyService;
import com.gitee.sop.notify.api.req.NotifyRequest;
import com.gitee.sop.notify.api.resp.NotifyResponse;
import com.gitee.sop.notifyexample.open.req.CreateOrderRequest;
import com.gitee.sop.support.context.OpenContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * 订单服务，回调处理
 *
 * @author 六如
 */
@Service
@Slf4j
public class OrderService {

    @DubboReference
    private NotifyService notifyService;

    /**
     * 下单成功
     *
     * @param request     入参
     * @param openContext 开放平台上下文
     * @return 返回订单编号
     */
    public String createOrder(CreateOrderRequest request, OpenContext openContext) {
        // 处理业务，回调客户端
        // 生成一个业务编号
        String orderNo = UUID.randomUUID().toString();
        log.info("生成订单，编号：{}", orderNo);
        // 模拟业务处理耗时
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 发送回调
        this.sendNotifyTask(request, openContext, orderNo);
        return orderNo;
    }

    private void sendNotifyTask(CreateOrderRequest request, OpenContext openContext, String orderNo) {
        // 回调
        NotifyRequest notifyRequest = new NotifyRequest();
        notifyRequest.setAppId(openContext.getAppId());
        notifyRequest.setApiName(openContext.getApiName());
        notifyRequest.setVersion(openContext.getVersion());
        notifyRequest.setClientIp(openContext.getClientIp());
        notifyRequest.setNotifyUrl(openContext.getNotifyUrl());
        notifyRequest.setCharset(openContext.getCharset());
        Map<String, Object> bizParams = new HashMap<>();
        bizParams.put("orderNo", orderNo);
        bizParams.put("msg", "success");
        bizParams.put("price", "100");
        notifyRequest.setBizParams(bizParams);
        notifyRequest.setRemark("下单回调");

        // 发送回调任务
        NotifyResponse notifyResponse = notifyService.notify(notifyRequest);
        log.info("回调返回,notifyResponse={}", notifyResponse);
        if (notifyResponse.getSuccess()) {
            log.info("保存notifyId到数据库, notifyId={}", notifyResponse.getNotifyId());
        }
    }

}
